﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections;
using IBatisNet.DataMapper.Configuration;
using IBatisNet.DataMapper;

using VehicleManagement.Codes;
using VehicleManagement.Models;
using VehicleManagement .ControllersServices;

namespace VehicleManagement.Controllers
{
    //[CustomerAuthorize(Roles = "负责人")]
    public class CarInfoController : Controller
    {
        const int PAGE_MAX = 8;
        //
        // GET: /CarInfo/
        CarInfoServices carInfoServices = new CarInfoServices();



        public ActionResult Index()
        {
            Hashtable ht = new Hashtable();
            SearchCarByRequeast(ref ht);
            int page;
            if (!string.IsNullOrWhiteSpace(Request.Params["Page"]))
                page = int.Parse(Request.Params["Page"]);
            else
                page = 1;
        ///IList<CarInfo> lstModel = carInfoServices .GetAllCarsInfo();lstModel.ToList()
            return View(carInfoServices.SearchAllCar(ht, (page - 1) * PAGE_MAX, PAGE_MAX));
        }
        /// <summary>
        /// 搜索车辆
        /// </summary>
        /// <param name="ht"></param>
        [NonAction]
        private void SearchCarByRequeast(ref Hashtable ht)
        {

            string carnum = Request.Params["CarNum"];
            string carAvailable = Request.Params["CarAvailable"];
            string caratate = Request.Params["CarState"];
            string cartype = Request.Params["CarType"];

            string carNumForSearch = "%%";
            string carTypeForSearch = "%%";
            string carStateForSearch = "%%";
            int carAvailableForSearch = 3;
            string companyName = "%%";
            if (Session["CompanyName"].ToString() != null)
            {
                companyName = Session["CompanyName"].ToString();
            }
            if (carAvailable == "是")
                carAvailableForSearch = 0;
            else if (carAvailable == "否")
                carAvailableForSearch = 1;

            if (!string.IsNullOrEmpty(carnum) && carnum != "车牌号")
                carNumForSearch = string.Format("%{0}%", carnum);
            if (!string.IsNullOrEmpty(cartype) && cartype != "车辆类型")
                carTypeForSearch = string.Format("%{0}%", cartype);
            if (!string.IsNullOrEmpty(caratate) && caratate != "是否可用")
                carStateForSearch = string.Format("%{0}%", caratate);

            ht.Add("carNumForSearch", carNumForSearch);
            ht.Add("carTypeForSearch", carTypeForSearch);
            ht.Add("carStateForSearch", carStateForSearch);
            ht.Add("carAvailableForSearch", carAvailableForSearch);
            ht.Add("companyName", companyName);
        }

        /// <summary>
        /// 增加新车辆
        /// </summary>
        /// <returns>返回增加新车辆的视图</returns>
        public ActionResult Create()
        {
            return View();
        }


        [HttpPost]
        public ActionResult Create(CarInfo carinfo)
        {
            if (ModelState.IsValid)
            {
                carinfo.CompanyName = Session["CompanyName"].ToString();
                object obj = carInfoServices.CreateCar(carinfo);
                return RedirectToAction("Index");
            }
            else
            return View(carinfo);
 
        }
        //
        // GET: /CarInfo/Details/5

        public ViewResult Details(int id)
        {

        CarInfo car = carInfoServices .GetCarInfoByID(id);
            return View(car);
        }

        /// <summary>
        /// 编辑车辆的信息
        /// </summary>
        /// <param name="id">车辆的ID</param>
        /// <returns>返回编辑车辆的信息视图</returns>
        public ActionResult Edit(int id)
        {
            CarInfo carInfo =carInfoServices.GetCarInfoByID(id);
            return View(carInfo);
        }
        [HttpPost]
        public ActionResult Edit(CarInfo carinfo)
        {
            //  if (ModelState.IsValid)
            // {
            int rows = carInfoServices.EditCar(carinfo);
            if (rows == 1)
                return RedirectToAction("Index");
            // }
            else
                return View(carinfo);

        }

        /// <summary>
        /// 删除车辆
        /// </summary>
        /// <param name="id">车辆的ID</param>
        /// <returns>返回删除车辆的信息视图</returns>
        public ActionResult Delete(int id)
        {
            CarInfo carInfo = carInfoServices.GetCarInfoByID(id);
            return View(carInfo);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            if (Request.IsAjaxRequest())
            {
                int i =carInfoServices.DeleteCar(id);//根据司机ID，删除
                if (i == 1)//删除成功
                {
                    return Json(new { Result = "true", Message = "删除成功" });
                }
                else//删除不成功
                {
                    return Json(new { Result = "false", Message = "删除失败" });
                }
            }
            else
            {
                return Json(new { Result = "false", Message = "该方法只能通过AJAX方式调用" });
            }

        }




        /// <summary>
        /// 选折可用的车辆
        /// </summary>
        /// <param name="id">1为可用，0不可用，默认选出的是可用的车辆</param>
        /// <returns></returns>
        //public ActionResult SelectCarByAvailable(int id = 1)
        //{
        //IList<CarInfo> lstModel = carInfoServices .GetCarsIsAvailable(id); 
        //    return View(lstModel.ToList());
        //}

        /// <summary>
        /// 根据车牌号查找车辆
        /// </summary>
        /// <param name="number">车牌号</param>
        /// <returns></returns>
        //public ActionResult SelectCarByNumber(string number = "SJ001")
        //{

        //CarInfo carInfo = carInfoServices .GetCarsByNumber(number);
        //    return View(carInfo);

        //}

        /// <summary>
        /// 根据车辆类型查找车辆
        /// </summary>
        /// <param name="number">车辆类型</param>
        /// <returns></returns>
        //public ActionResult SelectCarByType(string type = "校车")//参数为示范
        //{
          
        //    return View(carInfoServices.GetCarsByType(type));

        //}
        [ActionName("GetPagingInfo"),HttpGet]
        public ActionResult GetPagingInfo()
        {
            int currentPage;
            if (string.IsNullOrWhiteSpace(Request.Params["Page"]))
                currentPage = 1;
            else
                currentPage = int.Parse(Request.Params["Page"]);

            Hashtable ht = new Hashtable();
            SearchCarByRequeast(ref ht);
            int itemCount = carInfoServices.CountAllCar(ht);
            return Json(new
            {
                TotalItems = itemCount,
                ItemsPerPage = PAGE_MAX,
                CurrentPage = currentPage,
                TotalPages = (int)Math.Ceiling((decimal)itemCount / PAGE_MAX)
            },JsonRequestBehavior.AllowGet);
        }

        //获取（公司）所有车辆的车牌号码
        // POST: /CarInfo/GetCarNumberList
        [HttpPost, ActionName("GetCarNumberList")]
        public ActionResult GetCarNumberList()
        {
            string companyName = Session["CompanyName"].ToString();
            IList<string> list = SqlMapperManager.Instance.Get().QueryForList<string>("SELECT_ALL_CARNUM", companyName);
            return Json(list);
        }

        //根据车辆状态（忙碌或空闲），获取（公司）所有车辆的车牌号
        // POST: /CarInfo/GetCarsAvailable
        [HttpPost, ActionName("GetCarsAvailable")]
        public ActionResult GetCarsAvailable(int state)
        {
            Hashtable ht = new Hashtable();
            ht.Add("companyName", Session["CompanyName"].ToString());
            ht.Add("state",state);
            IList<string> list = SqlMapperManager.Instance.Get().QueryForList<string>("SELECT_CARNUM_BY_AVAILABLE", ht);
            return Json(list);
 
        }


        /// <summary>
        /// 验证车辆的唯一性
        /// </summary>
        /// <param name="CarNumber">车牌号码</param>
        /// <returns>Json字符串提示</returns>
        [HttpGet]
        public ActionResult CheckCarNumberExists(CarInfo carinfo)
        {
            Hashtable ht = new Hashtable();
            string companyName = Session["CompanyName"].ToString();
            ht.Add("companyName", companyName);
            ht.Add("carID", carinfo.CarID);
            IList<string> list = SqlMapperManager.Instance.Get().QueryForList<string>("SELECT_ALL_CarNumber_CHECK", ht);
            bool exists = string.IsNullOrEmpty(list.FirstOrDefault(u => u.ToLower() == carinfo.CarNumber.ToLower())) == false;
            return Json(!exists, JsonRequestBehavior.AllowGet);

        }



    }
}
